package com.hxkj.client.service.taglib.directive;


import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.client.service.ContentMappingServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.enums.ColumnExceptionEnum;
import com.hxkj.domain.po.*;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.exception.CustomException;
import com.platform.common.domain.result.ResultDataStruct;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.*;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_COLUMN_ARTICLELIST;

/**
 * @ClassName ColumnArticleListDirective 单个分类文章列表标签解析
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/9/12 18:18
 * @Version 1.0
 */
@Component
@Log4j
public class ColumnArticleListDirective extends AbstractDirective {

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private ContentMappingServiceClient contentMappingServiceClient;

    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取起始条数
     */
    public static final String START = "start";

    /**
     * 输入参数，获取置顶条数条数
     */
    public static final String IS_STICK_COUNT = "isStickCount";

    /**
     * 输入参数，获取条数
     */
    public static final String COUNT = "count";


    /**
     * 当前分类的文章列表
     */
    public static final String COLUMN_ARTICLE = "column";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        env.getOut();
        try {
            //Mr.zheng:获取参数
            Long columnId = super.getLong(COLUMN_ID, params) == null ? (Long) getCustomAttrbute(env, COLUMN_ID) : super.getLong(COLUMN_ID, params);
            Long siteId = super.getLong(SITE_ID, params) == null ? (Long) getCustomAttrbute(env, SITE_ID) : super.getLong(SITE_ID, params);
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? "update_time DESC" : super.getString(SORT, params);
            //Mr.zheng:默认取5条文章
            int start = super.getInt(START, params) == null ? 1 : super.getInt(START, params);
            //Mr.zheng:默认取3条置顶文章
            int isStickCount = super.getInt(IS_STICK_COUNT, params) == null ? 0 : super.getInt(IS_STICK_COUNT, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 5 : super.getInt(COUNT, params);
            String note = super.getNote(env);
            if (columnId == null) {
                log.info("分类ID为空");
            }

            Column column = new Column();
            column.setColumnId(columnId);
            column.setSiteId(siteId);
            ResultDataStruct<List<Column>> resultDataStruct = columnServiceClient.getColumnList(column);
            List<Column> columnList = resultDataStruct.getData();
            if (columnList != null && columnList.size() > 0) {
                column = columnList.get(0);
            }

            ContentMapping contentMapping = new ContentMapping();
            contentMapping.setColumnId(columnId);
            ResultDataStruct<List<ContentMapping>> resultDataStruct1 = contentMappingServiceClient.getContentMappingList(contentMapping);
            List<ContentMapping> contentMappingList = new ArrayList<>();
            if (resultDataStruct1.getData() != null) {
                contentMappingList = resultDataStruct1.getData();
            }

            Article article = new Article();

            article.setSiteId(column.getSiteId());
            article.setColumnId(column.getColumnId());
            article.setSort(sort);
            article.setStart(start - 1);
            List<Article> articleList = new ArrayList<>();
            String articleIds = "";

            articleList = getColumnASArticleList(isStickCount, count, article, articleList, articleIds);

            if (contentMappingList != null && contentMappingList.size() > 0) {
                for (Article art : articleList) {
                    art.setSiteId(siteId);
                    setContentMap(art, contentMappingList);
                }
            }

            if (StringUtils.isNotBlank(note)) {
                WebsiteAddr websiteAddr = getWebSiteAddr(siteId);
                column.setManuscriptPath(websiteAddr.getIpAdd() + column.getManuscriptPath());
                for (Article artic : articleList) {
                    artic.setManuscriptPath(websiteAddr.getIpAdd() + article.getManuscriptPath());
                }
            }else {
                // 静态文件文章链接加前缀
                Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
                Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
                for (Article item : articleList) {
                    String urlContext = siteCtxMap.get(item.getSiteId());
                    if(StringUtils.isNotBlank(urlContext)) {
                        item.setManuscriptPath(urlContext + item.getManuscriptPath());
                    }
                }
            }
            column.setArticleList(articleList);//封装该分类的文章列表

            env.setVariable(COLUMN_ARTICLE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(column));
            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_COLUMN_ARTICLELIST, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(COLUMN_ID, String.valueOf(super.getLong(COLUMN_ID, params)));
                    maps.put(SORT, String.valueOf(super.getString(SORT, params)));
                    maps.put(IS_STICK_COUNT, String.valueOf(super.getInt(IS_STICK_COUNT, params)));
                    maps.put(COUNT, String.valueOf(super.getInt(COUNT, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                throw new RuntimeException("分类所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
